import React from "react";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useRequest } from "ahooks";
import { CustomDatePicker } from "@/components/ui/datepicker";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Skeleton } from "@/components/ui/skeleton";
import {
  VbpDayStatsI,
  VbpStatsByCadnI,
  VbpStatsByHisCodeI,
  VbpStatsByStatsDateI,
  VbpStatsByDeptI,
} from "../../types/api";
import {
  getVbpBatchEndDateList,
  getVbpStatsByHisCode,
  getVbpStatsByCadn,
  getVbpStatsByCadnDept,
  getVbpStatsByStatsDate,
} from "../../api";
import { dayjs } from "../../App";
import { useLocation, useNavigate } from "react-router-dom";
// import ChartByDept from "./components/chart_by_dept";
import BarChartByCadnGroup from "./components/bar_chart_by_cadn_group";
import BarChartByCadnGroupDept from "./components/bar_chart_by_cadn_group_dept";
import BarChartByHisCode from "./components/bar_chart_by_his_code";
import LineChartByStatsDate from "./components/line_chart_by_stats_date";
import { useToast } from "@/hooks/use-toast";

const formSchema = z.object({
  startDate: z.date(),
  endDate: z.date(),
});

const defaultValues = {
  startDate: dayjs("2023-01-01").toDate(),
  endDate: dayjs().toDate(),
};
console.log(defaultValues);

const VbpStats = (): JSX.Element => {
  const location = useLocation();
  const navigate = useNavigate();
  const [vbpBatchEndDateList, setVbpBatchEndDateList] = React.useState<
    VbpStatsByHisCodeI[]
  >([]);
  const [vbpStatsList, setVbpStatsList] = React.useState<VbpStatsByHisCodeI[]>(
    []
  );
  const [vbpStatsByCadnList, setVbpStatsByCadnList] = React.useState<
    VbpStatsByCadnI[]
  >([]);
  const [vbpStatsByDeptList, setVbpStatsByDeptList] = React.useState<
    VbpStatsByDeptI[]
  >([]);
  const [vbpStatsByStatsDateList, setVbpStatsByStatsDateList] = React.useState<
    VbpStatsByStatsDateI[]
  >([]);
  const { toast } = useToast();

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  // 2. Define a submit handler.
  function onSubmit(values: z.infer<typeof formSchema>) {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    console.log(values);
    const params = new URLSearchParams();
    params.set("startDate", JSON.stringify(values.startDate));
    params.set("endDate", JSON.stringify(values.endDate));

    navigate(`${location.pathname}?${params.toString()}`);
    runByHisCode(params.toString());
    runByCadn(params.toString());
    runByDept(params.toString());
    runByStatsDate(params.toString());
  }

  // 获取可视化数据，一次取全部
  const { loading: loadingEndDateList, run: runEndDateList } = useRequest(
    (paramsString: string) => getVbpBatchEndDateList(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        // console.log(resp);
        setVbpBatchEndDateList(resp.data.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取数据失败",
        });
      },
    }
  );

  // 获取可视化数据，一次取全部
  const { loading: loadingChartData, run: runByHisCode } = useRequest(
    (paramsString: string) => getVbpStatsByHisCode(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        console.log(resp);
        setVbpStatsList(resp.data.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取数据失败",
        });
      },
    }
  );

  const { run: runByCadn } = useRequest(
    (paramsString: string) => getVbpStatsByCadn(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        console.log(resp);
        setVbpStatsByCadnList(resp.data.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取数据失败",
        });
      },
    }
  );

  const { run: runByDept } = useRequest(
    (paramsString: string) => getVbpStatsByCadnDept(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        console.log(resp);
        setVbpStatsByDeptList(resp.data.data);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "获取数据失败",
        });
      },
    }
  );

  const { run: runByStatsDate } = useRequest(
    (paramsString: string) => getVbpStatsByStatsDate(paramsString),
    {
      manual: false,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp: any, params: any) {
        console.log(resp);
        setVbpStatsByStatsDateList(resp.data.data);
      },
      onError(e: any, params: any) {
        // message.error("获取数据失败");
      },
    }
  );

  return (
    <div className="w-full p-6">
      <div className="w-full py-6 border p-3">
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex items-center space-x-4"
          >
            <FormField
              control={form.control}
              name="startDate"
              render={({ field }) => (
                <FormItem>
                  {/* <FormLabel>开始时间</FormLabel> */}
                  <FormControl>
                    <CustomDatePicker
                      placeholder="开始时间"
                      value={field.value}
                      onChange={field.onChange}
                      startMonth={dayjs().subtract(2, "day").toDate()}
                      endMonth={dayjs().add(1, "years").toDate()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="endDate"
              render={({ field }) => (
                <FormItem>
                  {/* <FormLabel>结束时间</FormLabel> */}
                  <FormControl>
                    <CustomDatePicker
                      placeholder="结束时间"
                      value={field.value}
                      onChange={field.onChange}
                      startMonth={dayjs().subtract(2, "years").toDate()}
                      endMonth={dayjs().add(1, "years").toDate()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <Button type="submit">查询</Button>
          </form>
        </Form>
      </div>

      <div>
        <div id="chartContainer" className="w-full">
          {/* <div className="text-center">
            <h3 className="text-2xl font-bold">中选品种完成情况</h3>
            {vbpStatsList.length > 0 ? (
              <BarChartByHisCode data={vbpStatsList} />
            ) : (
              <Skeleton className="w-[1024] h-[748] rounded-full" />
            )}
          </div> */}
          <div className="text-center">
            <h3 className="text-2xl font-bold">按药学分组统计</h3>
            <BarChartByCadnGroup data={vbpStatsByCadnList} />
          </div>
          <div className="text-center">
            <h3 className="text-2xl font-bold">科室集采药品完成情况统计</h3>
            <BarChartByCadnGroupDept data={vbpStatsByDeptList} />
          </div>
          {/* <div className="text-center">
            <h3 className="text-2xl font-bold">集采相关药品使用过程</h3>
            <LineChartByStatsDate data={vbpStatsByStatsDateList} />
          </div> */}
        </div>
      </div>
    </div>
  );
};

export default VbpStats;
